#!/usr/bin/env python
# -*- coding:utf-8 -*-

# file:userTokenService.py
# author:PigKnight
# datetime:2022/2/22 21:52
# software: PyCharm
"""
this is function description
"""

from authlib.jose import jwt
from flask import current_app

from utils.response_code import RET


class UserTokenService:

    # token生成
    @classmethod
    def create_token(cls, _userid, _username, _usertype):
        """
        生成新的token
        :param _userid:用户id
        :param _username:用户name
        :param _usertype: 用户type
        :return: token
        """
        # header
        header = {
            "alg": "HS256",
            "typ": "JWT",
            "exp": current_app.config["TOKEN_EXPIRES"],
        }

        payload = {
            "user_id": _userid,
            "account": _username,
            "user_type": _usertype,
        }
        token = jwt.encode(header=header, payload=payload, key=current_app.config["SECRET_KEY"])

        return token.decode("ascii")

    # 根据token获取用户信息
    @classmethod
    def get_user_by_token(cls, token):
        """
        校验token
        :param token:token值
        :return: 用户信息 or None
        """
        try:
            # 参数为私有密钥，与生成token的密钥一致
            payload = jwt.decode(token, key=current_app.config["SECRET_KEY"])

            return {'code': RET.OK, 'message': 'OK', 'data': payload}
        except Exception as e:
            return {'code': RET.SESSIONERR, 'message': '用户未登录或登录已过期', 'error': '用户未登录或登录已过期'}
